package service

import (
	"errors"
	"gin-vue-admin/global"
	"gin-vue-admin/model"
	"gin-vue-admin/model/request"

	"gorm.io/gorm"
)

// 获取部门列表
func GetPostInfoList(info request.QueryPost) (list interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.PageNum - 1)
	db := global.GVA_DB.Model(&model.SysPost{})
	var postList []model.SysPost

	if info.PostCode != "" {
		db = db.Where("`post_code` LIKE ?", "%"+info.PostCode+"%")
	}
	if info.PostName != "" {
		db = db.Where("`post_name` LIKE ?", "%"+info.PostName+"%")
	}
	if info.Status != "" {
		db = db.Where("`status` = ?", info.Status)
	}

	_ = db.Count(&total).Error
	err = db.Limit(limit).Offset(offset).Find(&postList).Error
	return postList, total, err
}

// 新增部门
func CreatePost(post model.SysPost) (err error) {
	db := global.GVA_DB.Model(&model.SysPost{})
	if !errors.Is(db.First("post_name = ?", post.PostName).Error, gorm.ErrRecordNotFound) {
		return errors.New("部门名称已存在")
	}
	if !errors.Is(db.First("post_code = ?", post.PostCode).Error, gorm.ErrRecordNotFound) {
		return errors.New("岗位编码已存在")
	}

	err = db.Create(&post).Error
	return err
}

// 查询部门
func QueryPost(id uint64) (post model.SysPost, err error) {
	err = global.GVA_DB.First(&post, id).Error
	return post, err
}

// 更新部门
func UpdatePost(post model.SysPost) (err error) {
	db := global.GVA_DB.Model(&model.SysPost{}).Where("post_id = ?", post.PostId)
	if errors.Is(db.Error, gorm.ErrRecordNotFound) {
		return errors.New("找不到对应的部门")
	}

	err = db.Updates(&post).Error
	return err
}

// 删除部门
func DeletePost(ids []uint64) (err error) {
	db := global.GVA_DB
	//if !errors.Is(db.First(&model.SysPost{}, "dept_id = ?", ids).Error, gorm.ErrRecordNotFound) {
	//	return errors.New("数据使用中无法删除")
	//}

	err = db.Where(ids).Delete(&model.SysPost{}).Error
	return err
}
